package com.codejiwei.flink.practice;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author jiwei
 * @description
 * @date 2023/5/23 15:19
 */
public class Flink_Windows_ProcessFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        env.socketTextStream("localhost", 8889)
                .flatMap((String line, Collector< Tuple2<String, Long> > out) -> {
                    Arrays.stream(line.split("\\W+")).forEach(word -> out.collect(Tuple2.of(word, 1L)));
                })
                .returns(Types.TUPLE(Types.STRING, Types.LONG))
                .keyBy(t -> t.f0)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<Tuple2<String, Long>, Tuple2<String, Long>, String, TimeWindow>() {
                    @Override
                    public void process(String key, Context context, Iterable<Tuple2<String, Long>> elements, Collector<Tuple2<String, Long>> out) throws Exception {
                        System.out.println(context.window().getStart());
                        long sum = 0L;
                        for (Tuple2<String, Long> element : elements) {
                            sum += element.f1;
                        }
                        out.collect(Tuple2.of(key, sum));
                    }
                })
                .print();

        env.execute();
    }
}
